import { Accessor, createSignal } from 'solid-js'
import { Show } from 'solid-js/web'
import type { ChatMessage } from '../types'
import MarkdownIt from 'markdown-it'
// @ts-ignore
import mdKatex from 'markdown-it-katex'
import mdHighlight from 'markdown-it-highlightjs'
interface Props {
  role: ChatMessage['role']
  message: Accessor<string> | string
}
export default function ChatMessage({ role, message }: Props) {
  const roleClass = {
    system: 'system',
    user: 'user',
    assistant: 'assistant',
  }
  const [isCopy, setIsCopy] = createSignal(false)

  function htmlString() {
    const md = MarkdownIt().use(mdKatex).use(mdHighlight)

    return typeof message === 'function' ? md.render(message()) : md.render(message)
  }
  function copyToClipboard() {
    const copyValue = typeof message === 'function' ? message() : message
    let oInput = document.createElement("textarea");
    oInput.value = copyValue;
    document.body.appendChild(oInput);
    oInput.select();
    oInput.setSelectionRange(0, oInput.value.length);//适配高版本ios
    document.execCommand("Copy");
    document.body.removeChild(oInput);
    setIsCopy(true)
    setTimeout(() =>{
      setIsCopy(false)
    },1000)
  }
  return (
    <div>
      <div class="flex py-2 gap-3 -mx-4 px-4 rounded-lg transition-colors md:hover:bg-slate/3"  class:user-box={ role === 'user' }>
        { role === 'user'? <div></div>:''} 
        <div class={ `"message prose text-slate break-words overflow-hidden border-radius ${ roleClass[role] }` } innerHTML={htmlString()} />
      </div>
      { role === 'assistant'? <div class='copy-text' onClick={copyToClipboard}>点我复制</div>:''} 
      <Show when={isCopy()}>
        <div class="transition-opacity is-alert is-copy">复制成功!</div>
      </Show>
    </div>
  )
}